/**
 * @desc 用户对应处理层
 */

import { ErrLogger } from '../middleware/logger';
import ErrorCode, { SuccessCode } from '../utils/errorCode';
import axios from 'axios';
const UserModel = require('../db/user');
const UserRelationModel = require('../db/userRelation');

// 异常code
const {
  ErrorSaveUserInfo,
  ErrorUserNotExistOpenid,
  ErrorUserVoted,
  ErrorUserVotParamErr,
  Error500,
} = ErrorCode;

interface User {
  id?: number;    //  必填  用户id
  openid: string; //  必填  用户openid
  nickname? :string; // (20)  必填  用户微信昵称
  name? :string; // (20)  必填  用户昵称
  phone?: string;  //(11)  必填  用户手机
  avater?: string; //(50)  必填  用户头像
  ticket?: number;  //  必填  用户当前票数
  picture?: string;  //(50)  必填  用户分享的照片
}

/**
 * 获取用户信息
 */
interface QueryInfo {
  nickname?: string;
}
export const CGetUserInfo = (info: QueryInfo = {}) => {
  return new Promise(async (resolve, reject) => {
    try {
      const { nickname } = info;
      const vParam: QueryInfo = {};
      if (nickname) {
        vParam['nickname'] = nickname;
      }
      const result = await UserModel.find(vParam);
      resolve({
        ...SuccessCode,
        obj: {
          userlist: result,
          total: result.length
        }
      })
    } catch (err) {
      ErrLogger({
        name: '获取用户信息',
        err,
      });
      reject(Error500);
    }
  });
}

/**
 * 用户信息操作
 * @param user 用户类型
 * @returns 
 */
export const CUserOption = (user: User) => {
  console.log(111);
  return new Promise(async (resolve, reject) => {
    const { openid } = user;
    // openid不存在
    if (!openid) {
      reject(ErrorUserNotExistOpenid);
      return;
    }
    try {
      const result = await UserModel.find({openid});
      if (result.length > 0) {
        // 用户存在，修改用户信息
        CUserModify(user).then(res => {
          resolve(res);
        }).catch(err => {
          reject(err)
        })
      } else {
        console.log(222);
        // 用户不存在直接插入
        CUserSave(user).then(res => {
          resolve(res);
        }).catch(err => {
          reject(err)
        })
      }
    } catch (err) {
      ErrLogger({
        name: '用户信息操作出错',
        err,
      });
      reject(Error500);
      return;
    }
  })
}

/**
 * 保存用户信息
 * @param user 用户类型
 * @returns 
 */
export const CUserSave = (user: User) => {
  return new Promise(async (resolve, reject) => {
    const { openid, nickname, name, phone, picture, avater } = user;
    // 报名信息不全
    if (!nickname || !phone || !picture) {
      reject(ErrorSaveUserInfo);
      return;
    }
    try {
      const vUserModel = new UserModel({
        openid,
        nickname,
        name,
        phone,
        picture,
        avater,
        ticket: 0,
      });
      await vUserModel.save();
      resolve({
        ...SuccessCode,
      });
    } catch (err: any) {
      ErrLogger({
        name: '保存用户信息出错',
        err,
      });
      reject(Error500);
    }
  });
}

/**
 * 修改用户信息
 * @param user 用户类型
 * @returns 
 */
export const CUserModify = (user: User) => {
  return new Promise(async (resolve, reject) => {
    const { openid, name, phone, picture } = user;
    try {
      await UserModel.updateOne({ openid }, { name, phone, picture });
      resolve({
        ...SuccessCode
      });
    } catch (err: any) {
      ErrLogger({
        name: '修改用户信息出错',
        err,
      });
      reject(Error500);
    }
  })
}

/**
 * 增加用户投票
 * @returns 
 */
export const CUserAddTicker = (openid: string, passopenid: string) => {
  return new Promise(async (resolve, reject) => {
    try {
      if (!openid || !passopenid) {
        reject(ErrorUserVotParamErr);
        return;
      }

      const result = await UserModel.find({ openid });
      // 判断openid是否存在，不存在则不能投票
      if (result.length > 0) {
        const vUserRelationResult = await UserRelationModel.find({ openid });
        // 判断用户之前是否投过票
        if (vUserRelationResult.length > 0) {
          // 获取用户存储在表中的时间戳
          const time = vUserRelationResult[0].time;
          // 获取当天凌晨0点的时间戳
          const vDate = new Date();
          const vTimeStamp = new Date(`${vDate.getFullYear()}-${vDate.getMonth() + 1}-${vDate.getDate()}`).getTime();
          // 如果当前用户的时间小于凌晨0点的时间戳的话，则可以继续投票
          if (time < vTimeStamp) {
            // 更新数据
            // 关系表中更新时间
            await UserRelationModel.updateOne({ openid }, { time: new Date().getTime() });
            // 用户表中更新票数
            await UserModel.updateOne({ passopenid }, { ticket: result[0].ticket + 1 });
            resolve({
              ...SuccessCode
            });
          } else {
            resolve(ErrorUserVoted);
          }
        } else {
          // 更新数据
          // 关系表中更新时间
          await UserRelationModel({
            openid,
            passopenid,
            time: new Date().getTime()
          })
          .save()
          // 用户表中更新票数
          await UserModel.updateOne({ passopenid }, { ticket: result[0].ticket + 1 });
          resolve({
            ...SuccessCode
          });
        }
      } else {
        ErrLogger({
          name: '增加用户投票出错——虚假openid',
          openid: `请求的openid为${openid}`,
          passopenid: `需要增加的passopenid为${passopenid}`
        });
        resolve(Error500);
      }
    } catch (err: any) {
      ErrLogger({
        name: '修改用户信息出错',
        err,
      });
      reject(Error500);
    }
  })
}

/**
 * 登录
 */
export const CLogin = (data: any) => {
  return new Promise(async (resolve, reject) => {
    try {
      const { sCode } = data
      console.log('sCode', sCode)
      const APPID = "wxe981841c8b4cdb53" 
      const APPSECRET = "9bab5415b9d121040cac7b4fbd0ce9cc"
      // 通过code换取网页授权access_token
      // https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${APPSECRET}&code=${sCode}&grant_type=authorization_code
      // const res = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${APPSECRET}&js_code=${sCode}&grant_type=authorization_code`)
      const authorizationRes = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${APPSECRET}&code=${sCode}&grant_type=authorization_code`)
      const { access_token, openid } = authorizationRes.data
      // console.log('access_token=', access_token)
      // console.log('openid=', openid)
      const userinfoRes = await axios.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`)
      const { nickname, headimgurl } = userinfoRes.data

      // 查询数据库中的name，phone，picture数据
      let name = '';
      let phone = '';
      let picture = '';
      const result = await UserModel.find({openid});
      if (result.length > 0) {
        name = result[0].name
        phone = result[0].phone
        picture = result[0].picture
      }
      console.log('result', { openid, nickname, headimgurl, name, phone, picture })
      resolve({
        ...SuccessCode,
        obj: { openid, nickname, headimgurl, name, phone, picture }
      })
      // console.log('openid=', userinfoRes)
    } catch (err) {
      ErrLogger({
        name: '登录出错',
        err,
      });
      reject(Error500);
    }
  });
}


// /**
//  * 关系用户登录（投票人）
//  */
// export const CRelationLogin = (data: any) => {
//   return new Promise(async (resolve, reject) => {
//     try {
//       const { sCode, openid: passopenid } = data
//       console.log('sCode', sCode)
//       const APPID = "wxe981841c8b4cdb53" 
//       const APPSECRET = "9bab5415b9d121040cac7b4fbd0ce9cc"
//       // 通过code换取网页授权access_token
//       const authorizationRes = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${APPSECRET}&code=${sCode}&grant_type=authorization_code`)
//       const { access_token, openid } = authorizationRes.data
//       const userinfoRes = await axios.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`)
//       const { nickname, headimgurl } = userinfoRes.data
//       // 保存用户信息
//       CRelationUserSave({openid, nickname, avater: headimgurl, passopenid})
//       resolve({
//         ...SuccessCode,
//         obj: { openid, nickname, headimgurl }
//       })
//     } catch (err) {
//       ErrLogger({
//         name: '登录出错',
//         err,
//       });
//       reject(Error500);
//     }
//   });
// }

// /**
//  * 保存关系用户（投票人）信息
//  * @param user 用户类型
//  * @returns 
//  */
// export const CRelationUserSave = (user: User) => {
//   return new Promise(async (resolve, reject) => {
//     const { openid, nickname, avater, passopenid } = user;
//     // 投票信息不全
//     if (!openid || !passopenid) {
//       reject(ErrorSaveUserInfo);
//       return;
//     }
//     try {
//       const vUserModel = new UserModel({
//         openid,
//         nickname,
//         name,
//         phone,
//         picture,
//         avater,
//         ticket: 0,
//       });
//       await vUserModel.save();
//       resolve({
//         ...SuccessCode,
//       });
//     } catch (err: any) {
//       ErrLogger({
//         name: '保存用户信息出错',
//         err,
//       });
//       reject(Error500);
//     }
//   });
// }